package xyz.zq.validation.aspect;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;
import org.springframework.validation.BindingResult;
import xyz.zq.validation.entity.User;
import xyz.zq.validation.exception.MyException;

@Aspect
@Component
public class MyAspect {


    @Pointcut("execution(public * xyz.zq.validation.controller.UserController.add(..))")
    public void valid() {
    }


    @Before("valid()")
    public void beforeHandlerControllerMethod(JoinPoint joinPoint) {


        System.out.println("start before");
        Object[] args = joinPoint.getArgs();
        User user = null;
        BindingResult result = null;
        for (Object o : args) {
            if (o instanceof User)
                user = (User) o;
            if (o instanceof BindingResult)
                result = (BindingResult) o;
        }

        if (null != result) {

            if (result.getErrorCount() > 0) {
                System.out.println("登录错误");
                System.out.println(user);
                throw new MyException(result);
            }

        }

        System.out.println("end before");

    }

    @After("valid()")
    public void afterHandlerControllerMethod(JoinPoint joinPoint) {

        System.out.println("start after");

        Object[] args = joinPoint.getArgs();
        for (Object o : args) {

            System.out.println("=======================");
            System.out.println(o);
        }

        System.out.println("end after");

    }


}
